import './types.tsx'
import {Component, createRef} from "react";
import {Data, State} from "./types.tsx";
import {Button, Col, DatePicker, Form, FormInstance, Row, Select, Slider, Space, Table, Tag} from "antd";
import {ColumnsType, TablePaginationConfig} from "antd/es/table";
import {DEFAULT_PAGINATION, fmtDate, fmtMoney, Handler, PageUtil, randomString} from "../../../utils/util.tsx";
import {send, URL} from "../../../utils/http.util.tsx";
import LazyIcon from "../../../components/Tools/Icon";

const {RangePicker} = DatePicker;


class RechargeOrder extends Component<any, State> {
    private statusOptions = []
    /** 查询表单的 Ref */
    formRef = createRef<FormInstance>()

    columns: ColumnsType<Data> = [
        {
            title: "商户订单号",
            dataIndex: "outTradeNo",
            key: "outTradeNo",
        },
        {
            title: "微信支付订单号",
            dataIndex: "transactionId",
            key: "transactionId",
        },
        {
            title: "充值金额",
            dataIndex: "amount",
            key: "amount",
            render: (value) => fmtMoney(value)
        },
        {
            title: "订单状态",
            dataIndex: "status",
            key: "status",
            render: (_, record) => {
                let color = 'red'
                if (record.status === 1) {
                    color = 'green'
                }
                return <Tag color={color}>{record.statusName}</Tag>
            }
        },
        {
            title: "支付时间",
            dataIndex: "payTime",
            key: "payTime",
            render: text => <>{fmtDate(text)}</>
        }
    ]

    state: State = {
        data: [],
        loading: false,
        pagination: DEFAULT_PAGINATION,
        statusOption: [],

        userId: undefined
    }

    refresh = (userId: string) => {
        this.setState({userId}, () => this.handleFetch())
    }

    componentDidMount = () => {
        if (!this.props.embedded) {
            this.handleFetch()
        }

        send(URL.rechargeOrderStatusOption).then((resp) => {
            const httpCode = resp.data.httpCode;
            if (httpCode === 200) {
                // @ts-ignore
                this.statusOptions = [{label: '全部', value: null}, ...resp.data.data]
            } else Handler.ofHttpWarn(httpCode)
        }).catch(Handler.ofError)
    }

    handleFetch(qo: any = undefined, pagination: TablePaginationConfig | undefined = undefined) {
        this.setState({loading: !this.state.loading})

        if (qo) {
            if (qo.payTimeArr) {
                qo.payTimeStart = qo.payTimeArr[0].valueOf()
                qo.payTimeEnd = qo.payTimeArr[1].valueOf()
                delete qo.payTimeArr;
            }
            if (qo.amountArr) {
                qo.amountStart = qo.amountArr[0].valueOf()
                qo.amountEnd = qo.amountArr[1].valueOf()
                delete qo.amountArr;
            }
        } else {
            qo = {}
        }

        if (this.state.userId) {
            qo.userId = this.state.userId
        }

        console.log(qo)

        send(URL.queryRechargeOrder, {...qo, ...PageUtil.toDto(pagination)}).then((resp) => {
            const httpCode = resp.data.httpCode;
            if (httpCode === 200) {
                const data = resp.data.data;
                this.setState(
                    {
                        data: data.records.map((item: { key: number, id: number }) => {
                                return {
                                    ...item,
                                    key: randomString()
                                }
                            }
                        ),
                        pagination: PageUtil.toPagination(data),
                        loading: false
                    }
                );
            } else Handler.ofHttpWarn(httpCode)
        }).catch(Handler.ofError)
    }

    render() {
        const {data, pagination, loading} = this.state;

        return (
            <>
                <Form ref={this.formRef} onFinish={(qo) => this.handleFetch(qo)} className="queryForm">
                    <Row gutter={24}>
                        <Col span={8}>
                            <Form.Item label="支付时间" name="payTimeArr">
                                <RangePicker showTime format="YYYY-MM-DD HH:mm:ss" placeholder={['开始时间', '结束时间']}/>
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="订单状态" name="status">
                                <Select defaultValue={null} options={this.statusOptions}/>
                            </Form.Item>
                        </Col>
                        <Col span={8}>
                            <Form.Item label="充值金额" name="amountArr">
                                <Slider range min={0} max={10000} tooltip={{formatter: fmtMoney}}/>
                            </Form.Item>
                        </Col>
                    </Row>
                    <Row gutter={24}>
                        <Col span={24}>
                            <Space size={"middle"} style={{float: "right"}}>
                                <Button icon={<LazyIcon iconName="ClearOutlined"/>} htmlType="button" onClick={() => this.formRef.current?.resetFields()}>重置</Button>
                                <Button icon={<LazyIcon iconName="SearchOutlined"/>} type="primary" htmlType="submit">查询</Button>
                            </Space>
                        </Col>
                    </Row>
                </Form>
                <Table loading={loading} dataSource={data} pagination={pagination} columns={this.columns} footer={() => `总共 ${this.state.pagination.total} 条数据`}
                       onChange={(pagination) => this.handleFetch(undefined, pagination)}/>
            </>
        )
    }
}

export default RechargeOrder;
